package com.yjd.comm.baseInfo.util;

import java.util.ArrayList;
import java.util.List;

import org.apache.log4j.Logger;

import com.yjd.comm.base.enums.DbWREnums;
import com.yjd.comm.baseInfo.model.HospitalModel;
import com.yjd.comm.baseInfo.service.IHospitalService;
import com.yjd.comm.cache.up.ICacheUpdate;
import com.yjd.comm.util.ServiceHolder;
import com.yjd.comm.util.StringUtil;

/**
 * <b>description</b>：医院信息工具类 <br>
 * <b>time</b>：2014-10-21上午10:58:20 <br>
 * <b>author</b>： ready likun_557@163.com
 */
public class HospitalUtil implements ICacheUpdate {

	private static Logger logger = Logger.getLogger(HospitalUtil.class);
	private static final String SERVICE = "hospitalService";

	/**
	 * 禁止直接访问该hospitalList的值,通过getHospitalList()来访问
	 */
	private static List<HospitalModel> hospitalList = null;

	private static IHospitalService getHospitalService() {
		return ServiceHolder.getService(IHospitalService.class, SERVICE);
	}

	/**
	 * 获取医院缓存数据
	 * 
	 * @return
	 * @throws Exception
	 */
	@SuppressWarnings("unchecked")
	public static List<HospitalModel> getHospitalList() throws Exception {
		if (hospitalList == null) {
			synchronized (HospitalUtil.class) {
				if (hospitalList == null) {
					hospitalList = getHospitalService().getModelList(null,DbWREnums.READ);
				}
			}
		}
		return hospitalList;
	}

	/**
	 * 模糊查询医院信息
	 * 
	 * @param query
	 * @param size
	 * @return
	 * @throws Exception
	 */
	public static List<HospitalModel> queryHospitalNames(String query, int size)
			throws Exception {
		List<HospitalModel> resultList = new ArrayList<HospitalModel>();
		if (StringUtil.isEmpty(query)) {
			return resultList;
		}
		List<HospitalModel> list = getHospitalList();
		int i = 1;
		for (HospitalModel hospitalModel : list) {
			if ((StringUtil.isNotEmpty(hospitalModel.getTitle()) && hospitalModel
					.getTitle().contains(query))
					|| (StringUtil.isNotEmpty(hospitalModel.getTitle_pinyin()) && hospitalModel
							.getTitle_pinyin().contains(query))) {
				resultList.add(hospitalModel);
				if (i++ == size) {
					break;
				}
			}
		}
		return resultList;
	}

	/**
	 * 更新医院缓存数据
	 */
	@SuppressWarnings("unchecked")
	@Override
	public void updateCache() {
		try {
			hospitalList = getHospitalService().getModelList(null,DbWREnums.READ);
			logger.info("更新医院数据缓存成功!");
		} catch (Exception e) {
			logger.error("更新医院数据缓存出错:" + e.getMessage(), e);
		}
	}

}
